package com.vegan_friendly;

import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.os.AsyncTask;
import android.os.Handler;

public class CommunicationManager {
	
	private final String SERVER_URL = "http://www.vegan-friendly.co.il/?vf_api=get_business_by_query";

	private static CommunicationManager m_Inst = null;
	private CommunicationManager(){
		
	}
	
	public static CommunicationManager Inst(){
		if(m_Inst==null)
			m_Inst = new CommunicationManager();		
		return m_Inst;
	}
	
	public boolean GetDataFromServer(){
		
		
		new GetDataTask().execute("");
		//new DownloadFilesTask().execute("test");
		
		return true;
	}
	
	 private class GetDataTask extends AsyncTask<String, Integer, Long> {
	     protected Long doInBackground(String... urls) {
	    	 
	    	 HttpClient httpclient = new DefaultHttpClient();
			    HttpResponse response;
			    String responseString = null;
			    try {
			        response = httpclient.execute(new HttpGet(SERVER_URL));
			        StatusLine statusLine = response.getStatusLine();
			        if(statusLine.getStatusCode() == HttpStatus.SC_OK){
			        	
			        	HttpEntity r_entity = response.getEntity();
			        	String xmlString = EntityUtils.toString(r_entity);
			            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			            DocumentBuilder db = factory.newDocumentBuilder();
			            InputSource inStream = new InputSource();
			            inStream.setCharacterStream(new StringReader(xmlString));
			            Document doc = db.parse(inStream);  
			            
			          
			            
			            DBAdapter.Inst().addRests(doc);
			            
			            
			            return (long)1;
			            
			            
			        } else{
			            //Closes the connection.
			            response.getEntity().getContent().close();
			            throw new IOException(statusLine.getReasonPhrase());
			        }
			    } catch (ClientProtocolException e) {
			        //TODO Handle problems..
			    } catch (IOException e) {
			        //TODO Handle problems..
			    } catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    	 //MainActivity.CloseProgress();
	         return (long) 1;
	     }

	     protected void onProgressUpdate(Integer... progress) {
	         //setProgressPercent(progress[0]);
	     }

	     protected void onPostExecute(Long result) {
	         //showDialog("Downloaded " + result + " bytes");
	    	 //MainActivity.CloseProgress();
	     }
	 }
	
	 private class DownloadFilesTask extends AsyncTask<String, Integer, Long> {
	     protected Long doInBackground(String... urls) {
	    	 
	    	 try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
	    	 //MainActivity.CloseProgress();
	         return (long) 1;
	     }

	     protected void onProgressUpdate(Integer... progress) {
	         //setProgressPercent(progress[0]);
	     }

	     protected void onPostExecute(Long result) {
	         //showDialog("Downloaded " + result + " bytes");
	    	 //MainActivity.CloseProgress();
	     }
	 }
}
